package com.bright.ghj.common.config;

import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

/**
 * @author Tz
 * @date 2024/02/26 16:01
 * @Description 网络请求配置
 *
 * RestTemplate 默认的 ClientHttpRequestFactor 为SimpleClientHttpRequestFactory，其中的 createRequest 方法，每次都会创建一个新的连接
 * <p>建立连接本身就是一个费时费力的操作，如果频繁地对一个接口发起调用，每次都创建连接会造成极大的资源浪费，而且若连接不能及时释放，就会因为无法建立新的连接导致后面的请求阻塞
 * <p>所有用上连接线程池
 */
@Configuration
public class RestTemplateConfig {

    @Value("${restTemplate.connection.connectRequestTimeout:1200000}")
    private Integer connectRequestTimeout;

    @Value("${restTemplate.connection.connectTimeout:3600000}")
    private Integer connectTimeout;

    @Value("${restTemplate.connection.readTimeout:3600000}")
    private Integer readTimeout;

    @Value("${restTemplate.connection.poolMaxTotal:400}")
    private Integer poolMaxTotal;

    @Value("${restTemplate.connection.poolDefaultMaxPerRoute:100}")
    private Integer poolDefaultMaxPerRoute;

    /**
     * 使用RestTemplateBuilder来实例化RestTemplate对象，spring默认已经注入了RestTemplateBuilder实例
     * @return
     */
    @Bean
    public RestTemplate restTemplate() {
        //配置HTTP超时时间
        HttpComponentsClientHttpRequestFactory httpRequestFactory = new HttpComponentsClientHttpRequestFactory();
        httpRequestFactory.setConnectionRequestTimeout(connectRequestTimeout);
        httpRequestFactory.setConnectTimeout(connectTimeout);
        httpRequestFactory.setReadTimeout(readTimeout);
        return new RestTemplate(httpRequestFactory);
    }


    @Bean
    public ClientHttpRequestFactory httpRequestFactory() {
        return new HttpComponentsClientHttpRequestFactory(httpClient());
    }

    @Bean
    public HttpClient httpClient() {
        Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http", PlainConnectionSocketFactory.getSocketFactory())
                .register("https", SSLConnectionSocketFactory.getSocketFactory())
                .build();
        PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(registry);
        //设置整个连接池最大连接数
        connectionManager.setMaxTotal(poolMaxTotal);

        //路由是对maxTotal的细分
        connectionManager.setDefaultMaxPerRoute(poolDefaultMaxPerRoute);
        RequestConfig requestConfig = RequestConfig.custom()
                //返回数据的超时时间
                .setSocketTimeout(readTimeout)
                //连接上服务器的超时时间
                .setConnectTimeout(connectTimeout)
                //从连接池中获取连接的超时时间
                .setConnectionRequestTimeout(connectRequestTimeout)
                .build();
        return HttpClientBuilder.create()
                .setDefaultRequestConfig(requestConfig)
                .setConnectionManager(connectionManager)
                .build();
    }
}
